package com.bafa.front.admin;

import com.bafa.dbcache.LeagueCache;
import com.bafa.exceptions.ErrorException;
import com.bafa.exceptions.TeamDoesNotExistException;

import com.bafa.objects.season.Season;
import com.bafa.services.RetrieveServices;
import com.bafa.services.FixtureServices;
import com.bafa.services.SeasonServices;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;

import java.io.InputStream;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.record.formula.functions.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class CreateAllServlet extends AdminServlet {
	public void doAdminEvent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			ErrorException {

		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			// Parse the request
			List items = upload.parseRequest(request);

			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();

				if (!item.isFormField()) {
					if (item.getName().indexOf("xls") < 1) {

					} else {
						try {
							InputStream uploadedStream = item.getInputStream();
							POIFSFileSystem fs = new POIFSFileSystem(
									uploadedStream);
							HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);

							/**
							 * *****************BEGIN SEASON
							 * DETAILS************************
							 */
							HSSFSheet seasonDetailsSheet = hssfworkbook
									.getSheetAt(0);

							// Get Season Name
							HSSFRow seasonNameRow = seasonDetailsSheet
									.getRow(0);
							HSSFCell seasonNameCell = seasonNameRow
									.getCell((short) 1);
							String seasonName = seasonNameCell
									.getRichStringCellValue().getString();

							// Get Season Year
							HSSFRow seasonYearRow = seasonDetailsSheet
									.getRow(2);
							HSSFCell seasonYearCell = seasonYearRow
									.getCell((short) 1);
							int seasonYear = (int) seasonYearCell
									.getNumericCellValue();

							// Get Number of Divisions
							HSSFRow numDivsRow = seasonDetailsSheet.getRow(3);
							HSSFCell numDivsCell = numDivsRow
									.getCell((short) 1);
							int numDivs = (int) numDivsCell
									.getNumericCellValue();

							// Get Cup or League
							HSSFRow cupLeagueRow = seasonDetailsSheet.getRow(1);
							HSSFCell cupLeagueCell = cupLeagueRow
									.getCell((short) 1);
							String cupLeague = cupLeagueCell
									.getRichStringCellValue().getString();

							Season season = SeasonServices.createSeason(
									seasonName, seasonYear, cupLeague, true,
									numDivs);
							/**
							 * *****************END SEASON
							 * DETAILS************************
							 */

							/**
							 * *****************BEGIN ADD FIXTURES AND
							 * TEAMS************************
							 */
							HSSFSheet fixturesSheet = hssfworkbook
									.getSheetAt(1);
							int rows = fixturesSheet.getPhysicalNumberOfRows();
							HashMap addedTeams = new HashMap();
							for (int r = 1; r < rows; r++) {
								try {
									HSSFRow row = fixturesSheet.getRow(r);
									String teamA = row.getCell((short) 2)
											.getRichStringCellValue()
											.getString();
									String teamB = row.getCell((short) 3)
											.getRichStringCellValue()
											.getString();
									int teamAId = RetrieveServices
											.getTeamByName(teamA.trim())
											.getId();
									int teamBId = RetrieveServices
											.getTeamByName(teamB.trim())
											.getId();

									int division = (int) row.getCell((short) 4)
											.getNumericCellValue();
									//int day = (int) row.getCell((short) 0)
										//	.getNumericCellValue();
									java.util.Date date = row.getCell((short) 0).getDateCellValue();
									java.util.Date time = row.getCell((short) 1).getDateCellValue();
									int hour = new Integer(time.getHours()).intValue();
									int minute = new Integer(time.getMinutes()).intValue();
									//int month = (int) row.getCell((short) 1)
											//.getNumericCellValue();
									//int year = (int) row.getCell((short) 2)
											//.getNumericCellValue();
									//int hour = (int) row.getCell((short) 3)
										//	.getNumericCellValue();
									//int minute = (int) row.getCell((short) 4)
										//	.getNumericCellValue();

									// add the team to the season if not already
									if (!addedTeams.containsKey(teamA)) {
										SeasonServices.addTeamToSeason(season
												.getId(), division, teamAId);
										addedTeams.put(teamA, teamA);
									}
									if (!addedTeams.containsKey(teamB)) {
										SeasonServices.addTeamToSeason(season
												.getId(), division, teamBId);
										addedTeams.put(teamB, teamB);
									}

									// Now add the fixture
									FixtureServices.addFixture(teamAId,
											teamBId, date.getDate(), date.getMonth(), date.getYear()+1900, hour,
											minute, season.getId(), division);

								} catch (TeamDoesNotExistException teamNotExist) {
									message.addError(teamNotExist.getTeamName()+ " does not exist and could not be added to season");
								}
							}
							/**
							 * ********************END ADD FIXTURES AND
							 * TEAMS*****************
							 */

							/**
							 * *********************BEGIN ADD CUP
							 * FIXTURES********************
							 */
							if (cupLeague.equalsIgnoreCase("CUP")) {
								HSSFSheet cupFixtureSheet = hssfworkbook
										.getSheetAt(2);
								int someRows = cupFixtureSheet
										.getPhysicalNumberOfRows();

								for (int r = 1; r < someRows; r++) {
									HSSFRow row = cupFixtureSheet.getRow(r);
									String teamA = "";
									String teamB = "";
									if (row.getCell((short) 8).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
										teamA = new Integer(((int) row.getCell(
												(short) 8)
												.getNumericCellValue()))
												.toString();
									else
										teamA = row.getCell((short) 8)
												.getRichStringCellValue()
												.getString();
									if (row.getCell((short) 9).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
										teamB = new Integer(((int) row.getCell(
												(short) 9)
												.getNumericCellValue()))
												.toString();
									else
										teamB = row.getCell((short) 9)
												.getRichStringCellValue()
												.getString();
									String cup = row.getCell((short) 2)
											.getRichStringCellValue()
											.getString();
									String name = row.getCell((short) 0)
											.getRichStringCellValue()
											.getString();
									int day = (int) row.getCell((short) 3)
											.getNumericCellValue();
									int month = (int) row.getCell((short) 4)
											.getNumericCellValue();
									int year = (int) row.getCell((short) 5)
											.getNumericCellValue();
									int hour = (int) row.getCell((short) 6)
											.getNumericCellValue();
									int minute = (int) row.getCell((short) 7)
											.getNumericCellValue();
									int roundId = (int) row.getCell((short) 1)
											.getNumericCellValue();
									FixtureServices.addRound(teamA, teamB, day,
											month, year, hour, minute, season
													.getId(), true, name, (cup
													.equalsIgnoreCase("CUP")),
											roundId);
								}

							}

							// LeagueCache.refreshSeason(season.getId());
							HttpSession session = request.getSession();
							session.removeAttribute("ALLSEASONS");
							url = "logon.bafa";
							uploadedStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}
			}
		} catch (FileUploadException e) {

		}
	}

}
